import { CaseEntity, CaseStatus } from '../entity/CaseEntity';
import { SuspectEntity } from '../entity/SuspectEntity';
import { VictimEntity } from '../entity/VictimEntity';
import { ClueEntity } from '../entity/ClueEntity';
import { EvidenceValue } from '../value/EvidenceValue';
import { CaseAnalysisService } from '../service/CaseAnalysisService';

// 案件聚合 - 作为一个完整的业务单元
export class CaseAggregate {
  private caseAnalysisService: CaseAnalysisService = new CaseAnalysisService();
  
  constructor(
    public caseEntity: CaseEntity,
    public suspects: SuspectEntity[] = [],
    public victims: VictimEntity[] = [],
    public clues: ClueEntity[] = [],
    public evidence: EvidenceValue[] = []
  ) {}
  
  // 添加嫌疑人
  public addSuspect(suspect: SuspectEntity): void {
    if (!this.suspects.find(s => s.id === suspect.id)) {
      this.suspects.push(suspect);
      if (!this.caseEntity.suspects.includes(suspect.id)) {
        this.caseEntity.suspects.push(suspect.id);
      }
    }
  }
  
  // 添加线索
  public addClue(clue: ClueEntity): void {
    if (!this.clues.find(c => c.id === clue.id)) {
      this.clues.push(clue);
      if (!this.caseEntity.clues.includes(clue.id)) {
        this.caseEntity.clues.push(clue.id);
      }
    }
  }
  
  // 添加证据
  public addEvidence(evidence: EvidenceValue): void {
    if (!this.evidence.find(e => e.id === evidence.id)) {
      this.evidence.push(evidence);
      if (!this.caseEntity.evidence.includes(evidence.id)) {
        this.caseEntity.evidence.push(evidence.id);
      }
    }
  }
  
  // 分析案件，更新嫌疑人嫌疑程度
  public analyzeCase(): void {
    this.suspects.forEach(suspect => {
      const newSuspicionLevel = this.caseAnalysisService.analyzeSuspicionLevel(
        suspect,
        this.clues,
        this.evidence
      );
      suspect.suspicionLevel = newSuspicionLevel;
    });
  }
  
  // 标记案件为已侦破
  public markAsSolved(guiltySuspectId: string): boolean {
    const suspect = this.suspects.find(s => s.id === guiltySuspectId);
    if (!suspect) {
      return false;
    }
    
    // 重置所有嫌疑人的犯罪标记
    this.suspects.forEach(s => s.isGuilty = false);
    // 标记指定嫌疑人为犯罪者
    suspect.isGuilty = true;
    // 更新案件状态
    this.caseEntity.status = CaseStatus.SOLVED;
    this.caseEntity.updateTime = new Date().toISOString();
    
    return true;
  }
  
  // 获取案件的解决进度
  public getProgress(): number {
    const interviewedSuspects = this.suspects.filter(s => s.interviewNotes !== '').length;
    const analyzedClues = this.clues.filter(c => c.analysisResult !== '').length;
    const analyzedEvidence = this.evidence.filter(e => e.analysisReport !== '').length;
    
    return this.caseAnalysisService.calculateCaseProgress(
      this.caseEntity,
      interviewedSuspects,
      analyzedClues,
      analyzedEvidence
    );
  }
}
